import axios from 'axios'
import { useAppStore } from '@/stores/app'
import { ElMessage, ElMessageBox } from 'element-plus'

// 创建 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 50000,
  headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const appStore = useAppStore()
    // 配置请求token
    if (appStore.token) {
      config.headers.Authorization = 'Bearer ' + appStore.token
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  (response) => {
    const result = response.data
    const config = response.config

    if (result.code == 0) {
      return result
    }

    if (result.code == 4 && config.url != '/app/menus') {
      ElMessageBox.confirm('当前页面已失效，请重新登录', '系统提示', {
        confirmButtonText: '立即登录',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          localStorage.clear()
          window.location.href = '/'
        })
        .catch(() => {})
      return Promise.reject(new Error(result.message || 'Error'))
    }

    ElMessage.error(result.message || '系统出错了')
    return Promise.reject(new Error(result.message || 'Error'))
  },
  (error) => {
    ElMessage.error(error.message)
    return Promise.reject(error)
  }
)

// 导出实例
export default service
